﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace WPFStudy.Extensions
{
    /// <summary>
    /// HyperLink 打开浏览器
    /// </summary>
    public class HyperlinkOpenBrowserCmd : ICommand
    {
        public event EventHandler? CanExecuteChanged;

        public bool CanExecute(object? parameter)
        {
            return true;
        }

        public void Execute(object? parameter)
        {
            try
            {
                if (parameter != null)
                {
                    //System.Diagnostics.Process.Start("explorer.exe",parameter.ToString());
                    string url = parameter.ToString(); 
                    Process p = new Process(); 
                    p.StartInfo.FileName = "cmd.exe"; 
                    p.StartInfo.UseShellExecute = false;    
                    //不使用shell启动
                    p.StartInfo.RedirectStandardInput = true;
                    //cmd接受标准输入
                    p.StartInfo.RedirectStandardOutput = false;
                    //不想听cmd讲话所以不要他输出
                    p.StartInfo.RedirectStandardError = true;
                    //重定向标准错误输出
                    p.StartInfo.CreateNoWindow = true;
                    //不显示窗口
                    p.Start();
                    //向cmd窗口发送输入信息 后面的&exit告诉cmd运行好之后就退出
                    p.StandardInput.WriteLine("start "+url + "&exit");
                    p.StandardInput.AutoFlush = true;
                    p.WaitForExit();
                    //等待程序执行完退出进程
                    p.Close();
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show($"打开连接失败:{ex?.Message}","失败",MessageBoxButton.OK,MessageBoxImage.Error);
            }
        }
    }
}
